package com.peas.platform.module.icims.base.auth.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Assert;
import com.peas.platform.framework.mybatisplus.domain.BaseDomain;
import com.peas.platform.framework.mybatisplus.po.BasePo;
import com.peas.platform.framework.mybatisplus.service.BaseServiceImpl;
import com.peas.platform.module.icims.base.auth.api.req.SaveRoleReq;
import com.peas.platform.module.icims.base.auth.controller.vo.RolePermissionVo;
import com.peas.platform.module.icims.base.auth.domain.RoleDomain;
import com.peas.platform.module.icims.base.auth.dto.RoleDto;
import com.peas.platform.module.icims.base.auth.dto.RolePermissionDto;
import com.peas.platform.module.icims.base.auth.service.RolePermissionService;
import com.peas.platform.module.icims.base.auth.service.RoleService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class RoleServiceImpl extends BaseServiceImpl<RoleDto> implements RoleService {

    @Resource
    private RoleDomain roleDomain;
    @Resource
    private RolePermissionService rolePermissionService;

    @Override
    public BaseDomain<RoleDto, ? extends BasePo> getDomain() {
        return roleDomain;
    }

    @Transactional
    @Override
    public void saveRole(SaveRoleReq vo) {
        RoleDto dto = BeanUtil.copyProperties(vo, RoleDto.class);
        int result = dto.getId() == null ? this.save(dto) : this.updateById(dto);
        Assert.isTrue(result > 0, "保存失败");
        List<RolePermissionDto> rpds = rolePermissionService.listByField("roleId", dto.getId());
        rolePermissionService.removeBatchByList(rpds);
        List<RolePermissionDto> rpdList = new ArrayList<>();
        CollUtil.forEach(vo.getPermissions(), (CollUtil.Consumer<RolePermissionVo>) (v, index) -> {
            RolePermissionDto rpd = new RolePermissionDto();
            rpd.setRoleId(dto.getId());
            rpd.setPermissionId(v.getPermissionId());
            rpdList.add(rpd);
        });
        rolePermissionService.saveBatch(rpdList);
    }
}
